<template>
  <div>
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>文章列表</span>
      </div>
      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="q" >
          <el-form-item label="文章分类">
            <el-select v-model="q.cate_id" placeholder="请选择分类" size="small">
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="发布状态" style="margin-left: 15px;">
            <el-select v-model="q.state" placeholder="请选择状态" size="small">
              <el-option label="已发布" value="已发布"></el-option>
              <el-option label="草稿" value="草稿"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" size="small" @click="getArtclList()">筛选</el-button>
            <el-button type="info" size="small" @click="resetList">重置</el-button>
          </el-form-item>
        </el-form>
        <!-- 发表文章的按钮 -->
        <el-button type="primary" @click="showDailog=true" size="small" class="btn-pub">发表文章</el-button>
      </div>
      <!-- 文章表格区域 -->
        <el-table :data="articleList" style="width: 100%;" border stripe>
          <el-table-column label="文章标题">
            <template #default="{row}">
              <el-link type="primary" @click="showDetail(row.id)">{{row.title}}</el-link>
            </template>
          </el-table-column>
          <el-table-column label="分类" prop="cate_name"></el-table-column>
          <el-table-column label="发表时间">
            <template #default={row}>
              <!-- {{row}} -->
              {{ getTime( row.pub_date)}}
            </template>
          </el-table-column>
          <el-table-column label="状态" prop="state"></el-table-column>
          <el-table-column label="操作">
            <template #default="{row}">
            <el-button type="danger" size="mini" @click="delArt(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      <!-- 分页区域 -->

        <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="q.pagenum"
              :page-sizes=" [2,4,10, 20, 30, 40,50]"
              :page-size="q.pagesize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>

      <!-- 发表文章对话框 -->
        <el-dialog  title="发表文章"  :visible.sync="showDailog"  fullscreen  :before-close="handleClose" >
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="文章名称" prop="title">
            <el-input v-model="ruleForm.title"></el-input>
          </el-form-item>
          <el-form-item label="文章分类" prop="cate_id">
            <el-select v-model="ruleForm.cate_id" placeholder="请选择文章分类" style="width:100%"> 
              <el-option v-for="item in cateList" :key="item.id" :label="item.cate_name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="文章内容"  prop="content">
            <!-- 使用 v-model 进行双向的数据绑定 -->
            <quill-editor v-model="ruleForm.content"></quill-editor>
          </el-form-item>
          <el-form-item label="文章封面">
              <!-- 用来显示封面的图片 -->
              <img src="../../../assets/images/cover.jpg" alt="" class="cover-img" ref="imgRef" />
              <br />
              <!-- 文件选择框，默认被隐藏 -->
              <input type="file" style="display: none;" accept="image/*" ref="iptFile" @change="chooseImg" />
              <!-- 选择封面的按钮 -->
              <el-button type="text" @click="$refs.iptFile.click()">+ 选择封面</el-button>
          </el-form-item>
           <el-form-item> 
              <el-button type="primary" @click="pubArticle('已发布')">发布</el-button>
              <el-button type="info" @click="pubArticle('草稿')">存为草稿</el-button>
          </el-form-item>
          </el-form>
        </el-dialog>

        <!-- 文章详情弹层 -->
        <el-dialog
          title="文章详情"
          :visible.sync="artShowDailog"
          width="60%">
          <!-- 查看文章详情的对话框 -->
            <h1 class="title">{{ artDetail.title }}</h1>
            <div class="info">
              <span>作者：{{ artDetail.nickname || artDetail.username }}</span>
               <br>
              <span>发布时间：{{getTime(artDetail.pub_date) }}</span>
              <br>
              <span>所属分类：{{ artDetail.cate_name }}</span>
              <br>
              <span>状态：{{ artDetail.state }}</span>
            </div>
            
            <!-- 分割线 -->
            <el-divider></el-divider>

            <img :src="'http://big-event-vue-api-t.itheima.net' + artDetail.cover_img" alt="" />

            <div v-html="artDetail.content"></div>
        </el-dialog>
    </el-card>
  </div>
</template>

<script>
// 导入默认的封面图片
import defaultImg from '@/assets/images/cover.jpg'
//导入格式化时间插件
import dayjs from 'dayjs'
export default {
  name: 'ArtList',
  created(){
    this.getArtList(),
    this.getArtclList()
  },
  data() {
    return { 
      artDetail:{},//文章详情
      artShowDailog:false,//文章详情开关
      currentPage:1,
      total: 0,//总数据条数
      articleList:[],//文章信息列表
      cateList:[],//文章分类
      showDailog:false,//添加文章弹层开关
      ruleForm:{
        title: '',
        cate_id: '',
        content: '',
        cover_img:null,
        state:'草稿'
      },
        // 查询参数对象
        q: {
          pagenum: 1,
          pagesize:10,
          cate_id: '',
          state: '',
        },
      rules:{
        title: [
        { required: true, message: '请输入分类名称', trigger: 'blur' },
        { min:1,max:30, message: '文章名必须是1-30位的非空字符', trigger: 'blur' }
        ],
        cate_id:[
        { required: true, message: '请选择分类名称', trigger: 'blur' },
        ] ,
         content:[
        { required: true, message: '请输入文章内容', trigger: ['blur','change'] },
        ] ,
      },
    }
  },
  methods:{
    //重置表单
    resetArtList(){
          this.ruleForm.cover_img=null
          this.$refs.ruleForm.resetFields()
          this.$refs.imgRef.src= defaultImg
          this.ruleForm.state='草稿'
    },
    //删除文章
    delArt(id){
      this.$confirm('确定删除吗?').then(async()=>{
        const {data:res} = await this.$axios.delete('/my/article/info',{params:{id}})
        if(res.code != 0)return this.$message.error(res.message)
        this.$message.success(res.message)
        if (this.articleList.length===1&& this.q.pagenum > 1) {
            this.q.pagenum--
        }
        this.getArtclList()
      }).catch(error=> error )
    },
    // 展示文章详情
    async showDetail(id) {
      this.artShowDailog=true
      // 请求详情数据
      const { data: res } = await this.$axios.get('/my/article/info', { params: { id } })
      if (res.code !== 0) return this.$message.error('获取文章详情失败!')
      this.artDetail = res.data
    },
    //重置
    resetList() {
  // 1. 重置查询参数对象
      this.q = {
        pagenum: 1,
        pagesize:10,
        cate_id: '',
        state: '',
      },
      // this.$refs.rest.resetFields()
      // 2. 重新发起请求
      this.getArtclList()
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.q.pagenum=1
      this.q.pagesize=val
      this.getArtclList()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.q.pagenum=val
      this.getArtclList()
    },
    //格式化时间
    getTime(time){
       return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    //获取文章列表数据
  async  getArtclList(){
    const {data:res} = await this.$axios.get('/my/article/list',{params:this.q})
    if(res.code === 0){
    this.articleList=res.data
    this.total=res.total
    }
  },
   //发布文章
    pubArticle(state){
      this.ruleForm.state=state
      // 兜底校验
      this.$refs.ruleForm.validate(async (valid)=>{
        if(!valid)return
        if (!this.ruleForm.cover_img) return this.$message.error('请上传封面')
        //转换FromData数据类型
         const fd = new FormData()
        //  fd.append("title",this.ruleForm.title)
        //  fd.append("cate_id",this.ruleForm.cate_id)
        //  fd.append("content",this.ruleForm.content)
        //  fd.append("cover_img",this.ruleForm.cover_img)
        //  fd.append("state",this.ruleForm.state)

        // 优化
        Object.keys(this.ruleForm).forEach(item =>{
          fd.append(item,this.ruleForm[item])
        })
         //发送请求
        const{data:res}= await this.$axios.post('/my/article/add',fd)
        if(res.code!=0)return this.$message.error(res.message)
          this.$message.success(res.message)
         //清空表单(图片清不掉)
          this.showDailog=false
          this.resetArtList()
          this.getArtclList()
      })
    },
    //选择图片 
    chooseImg(e){
      const files = e.target.files
      if (files.length) {
      this.ruleForm.cover_img=files[0]
      const url= URL.createObjectURL(files[0])
      this.$refs.imgRef.src=url
      }else{
      this.$refs.imgRef.src= defaultImg
      this.ruleForm.cover_img=null
      }
    },
    async getArtList(){
      const {data:res}= await this.$axios.get('/my/cate/list')
      this.cateList=res.data
      },
      handleClose() {
      this.$confirm('确定要关闭吗?').then(()=>{
        this.showDailog=false
      }).catch(err => err)
    }}
  }
</script>

<style lang="less" scoped>
.search-box {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  .btn-pub {
    margin-top: 5px;
  }
}
// 设置富文本编辑器的默认最小高度
/deep/ .ql-editor {
  min-height: 300px;
}
// 设置图片封面的宽高
.cover-img {
  width: 400px;
  height: 280px;
  object-fit: cover;
}
</style>